﻿using System.IO;
using System;
using System.Collections.Generic;
using System.Numerics;
namespace Primer
{
    internal partial class TumblerCollection
    {
        private long _positionOfIFrame;

        public enum FrameType : byte
        {
            I,
            B,
            M,
        }

        public void Write(string path)
        {
            if (!File.Exists(path))
                throw new InvalidOperationException();
            using (var w = new BinaryWriter(File.Open(path, FileMode.OpenOrCreate)))
                Write(w, Get(0));
        }

        public void Read(string path)
        {
            if (!File.Exists(path))
                return;
            using (var r = new BinaryReader(File.Open(path, FileMode.Open)))
                ID = Add(Read(r));
        }

        private void Write(BinaryWriter w, IEnumerable<BigInteger> values)
        {
            var s = w.BaseStream;
            var lastValue = (BigInteger)0;
            var f = FrameType.I;
            foreach (var value in values)
                switch (f)
                {
                    case FrameType.I: w.Write(lastValue = value); _positionOfIFrame = s.Position; break;
                    case FrameType.B: w.WriteVUInt64((ulong)(lastValue - value)); lastValue = value; break;
                    case FrameType.M: w.WriteMagic(); break;
                }
        }

        private IEnumerable<BigInteger> Read(BinaryReader r)
        {
            var s = r.BaseStream;
            var lastValue = (BigInteger)0;
            while (s.Position < s.Length)
                switch ((FrameType)r.ReadByte())
                {
                    case FrameType.I: yield return lastValue = r.ReadBigInteger(); _positionOfIFrame = s.Position; break;
                    case FrameType.B: yield return lastValue += r.ReadVUInt64(); break;
                    case FrameType.M: r.CheckMagic(); break;
                }
        }
    }
}
